package com.example.elm.First_Page;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.widget.TintableCheckedTextView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.example.elm.Home_Page.Check_Shop_Data_Page;
import com.example.elm.Home_Page.Set_Location_Page;
import com.example.elm.Location_Data;
import com.example.elm.Login.Login_Page;
import com.example.elm.R;
import com.example.elm.SQL.Connection_SQL;
import com.example.elm.Shop_Data;
import com.example.elm.ViewPagerAdapter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Home_Page extends Fragment {

    View root;
    TextSwitcher search_text;
    LinearLayout search, set_location, set_shop_data;
    ViewPager view_page;
    TextView location_text;

    Location_Data locationData;
    private int index = 0;
    boolean is_loading_data = false, is_login = false, is_loading_shop_data = false, is_new_custom = false;
    String[] search_name = new String[]{"摩尔汉堡", "堡革士", "一口星球寿司"};
    List<View> viewList = new ArrayList<>();
    String email = "";
    AlertDialog dialog;
    List<Shop_Data> shop_data = new ArrayList<>();
    double lat_temp = 0, lng_temp = 0;
    String weather = "";
    int hour = 0, min = 0;
    double surcharge = 0;
    int delivery_time = 0;
    String user_name = "", user_sex = "", user_phone_number = "";
    String[] should_push_fee_weather = new String[]{"雷阵雨", "中雨", "大雨", "暴雨", "大暴雨", "特大暴雨", "强阵雨", "强雷阵雨", "极端降雨", "中雨-大雨", "大雨-暴雨", "暴雨-大暴雨", "大暴雨-特大暴雨", "雨雪天气", "雨夹雪", "烈风", "风暴", "狂爆风", "飓风", "中雪", "大雪", "暴雪", "中雪-大雪", "大雪-暴雪", "沙尘暴", "强沙尘暴", "龙卷风", "强浓雾", "特强浓雾"};

    public Home_Page(Location_Data locationData) {
        this.locationData = locationData;
    }

    private class Loading_Is_Login_Thread extends Thread {
        @Override
        public void run() {
            is_loading_data = false;
            is_login = false;

            while (Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID) == null) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM user WHERE android_id = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID));
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        is_login = true;
                        email = set.getString("email");
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!is_login) {
                        Intent intent = new Intent(root.getContext(), Login_Page.class);
                        startActivity(intent);
                    }
                }
            });
        }
    }

    private class Loop_Text_Thread extends Thread {
        @Override
        public void run() {
            while(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        search_text.setText(search_name[index++ % search_name.length]);
                    }
                });
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private class Loading_Email_Thread extends Thread {
        @Override
        public void run() {
            is_loading_data = false;
            is_login = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM user WHERE android_id = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID));
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        is_login = true;
                        email = set.getString("email");
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (is_login) {
                        dialog.dismiss();
                        Intent intent = new Intent(root.getContext(), Set_Location_Page.class);
                        intent.putExtra("location", locationData.getLocation());
                        intent.putExtra("city", locationData.getCity());
                        intent.putExtra("email", email);
                        intent.putExtra("lat", locationData.getLat());
                        intent.putExtra("lng", locationData.getLng());
                        intent.putExtra("district", locationData.getDistrict());
                        startActivityForResult(intent, 1);
                    }
                }
            });
        }
    }

    private class Loading_Shop_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_shop_data = false;
            surcharge = 0;
            delivery_time = 0;
            lat_temp = 0;
            lng_temp = 0;
            weather = "";
            hour = 0;
            min = 0;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE shop_place = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, locationData.getProvince() + "/" + locationData.getCity() + "/" + locationData.getDistrict());
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        is_new_custom = true;
                        Shop_Data temp = new Shop_Data();
                        temp.setEmail(set.getString("email"));
                        temp.setShop_name(set.getString("shop_name"));
                        temp.setShop_star(set.getDouble("shop_star"));
                        temp.setShop_sold(set.getInt("shop_sold"));
                        temp.setApproved(set.getInt("approved"));
                        temp.setOpen_hour_1(set.getString("open_hour"));
                        temp.setClose_hour_1(set.getString("close_hour"));
                        temp.setOpen_hour_2(set.getString("open_hour2"));
                        temp.setClose_hour_2(set.getString("close_hour2"));
                        temp.setShop_image(set.getBytes("shop_picture"));
                        temp.setPacking_fee(set.getDouble("packing_fee"));

                        String sql2 = "SELECT * FROM merchant_food_business_licence WHERE email = ?;";
                        PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                        preparedStatement2.setString(1, set.getString("email"));
                        ResultSet set2 = preparedStatement2.executeQuery();
                        while (set2.next()) {
                            return_shop_lat(set2.getString("live_where"), locationData.getCity());
                            temp.setLat(lat_temp);
                            temp.setLng(lng_temp);
                        }

                        String sql3 = "SELECT * FROM merchant_reduce_the_delivery_fee WHERE email = ?;";
                        preparedStatement2 = connection.prepareStatement(sql3);
                        preparedStatement2.setString(1, set.getString("email"));
                        ResultSet set3 = preparedStatement2.executeQuery();
                        while (set3.next()) {
                            String start_year = "" + set3.getString("activity_start_day").charAt(0);
                            start_year += set3.getString("activity_start_day").charAt(1);
                            start_year += set3.getString("activity_start_day").charAt(2);
                            start_year += set3.getString("activity_start_day").charAt(3);

                            String start_month = "" + set3.getString("activity_start_day").charAt(5);
                            start_month += set3.getString("activity_start_day").charAt(6);

                            String start_day = "" + set3.getString("activity_start_day").charAt(8);
                            start_day += set3.getString("activity_start_day").charAt(9);

                            String end_year = "" + set3.getString("activity_end_day").charAt(0);
                            end_year += set3.getString("activity_end_day").charAt(1);
                            end_year += set3.getString("activity_end_day").charAt(2);
                            end_year += set3.getString("activity_end_day").charAt(3);

                            String end_month = "" + set3.getString("activity_end_day").charAt(5);
                            end_month += set3.getString("activity_end_day").charAt(6);

                            String end_day = "" + set3.getString("activity_end_day").charAt(8);
                            end_day += set3.getString("activity_end_day").charAt(9);

                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                                LocalDate start_date = LocalDate.of(Integer.parseInt(start_year), Integer.parseInt(start_month), Integer.parseInt(start_day));
                                LocalDate end_date = LocalDate.of(Integer.parseInt(end_year), Integer.parseInt(end_month), Integer.parseInt(end_day));
                                LocalDate today = LocalDate.now();
                                LocalDate today_date = LocalDate.of(today.getYear(), today.getMonth(), today.getDayOfMonth());

                                boolean is_between = (today_date.isAfter(start_date) || today_date.isEqual(start_date)) && (today_date.isBefore(end_date) || today_date.isEqual(end_date));

                                if (is_between) {
                                    if (set3.getInt("is_just_new_custom") == 1) {
                                        String sql4 = "SELECT * FROM `" + email + "_user_order` WHERE shop_email = ?;";
                                        PreparedStatement preparedStatement3 = connection.prepareStatement(sql4);
                                        preparedStatement3.setString(1, set.getString("email"));
                                        ResultSet set4 = preparedStatement3.executeQuery();
                                        while (set4.next()) {
                                            temp.setCan_reduce_the_delivery_fee(0);
                                            is_new_custom = false;
                                        }

                                        if (is_new_custom) {
                                            temp.setCan_reduce_the_delivery_fee(set3.getDouble("reduce_how_many_money"));
                                        }
                                    }
                                    else {
                                        temp.setCan_reduce_the_delivery_fee(set3.getDouble("reduce_how_many_money"));
                                    }
                                }
                                else {
                                    temp.setCan_reduce_the_delivery_fee(0);
                                }
                            }
                        }

                        String sql4 = "SELECT * FROM merchant_coupon_collect_and_get_give WHERE email = ?;";
                        preparedStatement2 = connection.prepareStatement(sql4);
                        preparedStatement2.setString(1, set.getString("email"));
                        ResultSet set4 = preparedStatement2.executeQuery();
                        while (set4.next()) {
                            temp.setCollect_reduce_how_many_money(set4.getInt("set_how_much_is_the_discount"));
                        }

                        String sql5 = "SELECT * FROM merchant_new_custom_receive_a_discount WHERE email = ?;";
                        preparedStatement2 = connection.prepareStatement(sql5);
                        preparedStatement2.setString(1, set.getString("email"));
                        ResultSet set5 = preparedStatement2.executeQuery();
                        while (set5.next()) {
                            String start_year = "" + set5.getString("activity_start_day").charAt(0);
                            start_year += set5.getString("activity_start_day").charAt(1);
                            start_year += set5.getString("activity_start_day").charAt(2);
                            start_year += set5.getString("activity_start_day").charAt(3);

                            String start_month = "" + set5.getString("activity_start_day").charAt(5);
                            start_month += set5.getString("activity_start_day").charAt(6);

                            String start_day = "" + set5.getString("activity_start_day").charAt(8);
                            start_day += set5.getString("activity_start_day").charAt(9);

                            String end_year = "" + set5.getString("activity_end_day").charAt(0);
                            end_year += set5.getString("activity_end_day").charAt(1);
                            end_year += set5.getString("activity_end_day").charAt(2);
                            end_year += set5.getString("activity_end_day").charAt(3);

                            String end_month = "" + set5.getString("activity_end_day").charAt(5);
                            end_month += set5.getString("activity_end_day").charAt(6);

                            String end_day = "" + set5.getString("activity_end_day").charAt(8);
                            end_day += set5.getString("activity_end_day").charAt(9);

                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                                LocalDate start_date = LocalDate.of(Integer.parseInt(start_year), Integer.parseInt(start_month), Integer.parseInt(start_day));
                                LocalDate end_date = LocalDate.of(Integer.parseInt(end_year), Integer.parseInt(end_month), Integer.parseInt(end_day));
                                LocalDate today = LocalDate.now();
                                LocalDate today_date = LocalDate.of(today.getYear(), today.getMonth(), today.getDayOfMonth());

                                boolean is_between = (today_date.isAfter(start_date) || today_date.isEqual(start_date)) && (today_date.isBefore(end_date) || today_date.isEqual(end_date));

                                if (is_between) {
                                    if (is_new_custom) {
                                        temp.setNew_custom_receive_reduce_how_many_money(set5.getInt("reduce_how_many_money"));
                                    }
                                    else {
                                        temp.setNew_custom_receive_reduce_how_many_money(0);
                                    }
                                }
                                else {
                                    temp.setCan_reduce_the_delivery_fee(0);
                                }
                            }

                        }

                        shop_data.add(temp);
                    }
                    is_loading_shop_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_shop_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WeatherSearchQuery query = new WeatherSearchQuery(locationData.getCity(), WeatherSearchQuery.WEATHER_TYPE_LIVE);
                    try {
                        WeatherSearch weatherSearch = new WeatherSearch(root.getContext());
                        weatherSearch.setOnWeatherSearchListener(new WeatherSearch.OnWeatherSearchListener() {
                            @Override
                            public void onWeatherLiveSearched(LocalWeatherLiveResult localWeatherLiveResult, int i) {
                                if (i == 1000) {
                                    if (localWeatherLiveResult != null && localWeatherLiveResult.getLiveResult() != null) {
                                        LocalWeatherLive weatherLiveResult = localWeatherLiveResult.getLiveResult();
                                        weather = weatherLiveResult.getWeather();
                                        for (int j = 0; j < should_push_fee_weather.length; j++) {
                                            if (should_push_fee_weather[j].equals(weather)) {
                                                surcharge += 1.5;
                                                delivery_time += 10;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

                            }
                        });
                        weatherSearch.setQuery(query);
                        weatherSearch.searchWeatherAsyn();
                    } catch (AMapException e) {
                        throw new RuntimeException(e);
                    }
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                        LocalDateTime now_time = LocalDateTime.now();
                        hour = now_time.getHour();
                        min = now_time.getMinute();
                        if (hour >= 21 || (hour >= 0 && hour <= 5)) {
                            surcharge += 1.5;
                            delivery_time += 10;
                        }
                    }

                    for (int i = 0; i < shop_data.size(); i++) {
                        View view = LayoutInflater.from(root.getContext()).inflate(R.layout.shop_view, null);
                        ImageView shop_image = view.findViewById(R.id.shop_image);
                        LinearLayout click_this_shop = view.findViewById(R.id.click_this_shop);
                        TextView shop_name = view.findViewById(R.id.shop_name);
                        TextView shop_star = view.findViewById(R.id.shop_star);
                        TextView shop_sold_in_month = view.findViewById(R.id.shop_sold_in_month);
                        TextView how_dollars_can_sold = view.findViewById(R.id.how_dollars_can_sold);
                        TextView how_many_delivery_fee = view.findViewById(R.id.how_many_delivery_fee);
                        TextView how_long = view.findViewById(R.id.how_long);
                        TextView how_far = view.findViewById(R.id.how_far);
                        LinearLayout is_open_new_custom_receive_a_discount = view.findViewById(R.id.is_open_new_custom_receive_a_discount);
                        TextView new_custom_receive_a_discount_text_view = view.findViewById(R.id.new_custom_receive_a_discount_text_view);
                        LinearLayout is_open_coupon_collect_and_get_give = view.findViewById(R.id.is_open_coupon_collect_and_get_give);
                        TextView coupon_collect_and_get_give_text_view = view.findViewById(R.id.coupon_collect_and_get_give_text_view);

                        try {
                            RouteSearch routeSearch = new RouteSearch(root.getContext());
                            routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
                                @Override
                                public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

                                }

                                @Override
                                public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

                                }

                                @Override
                                public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

                                }

                                @Override
                                public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
                                    if (i == 1000) {
                                        if (rideRouteResult != null) {
                                            System.out.println(rideRouteResult.getPaths().get(0).getDuration() / 60);
                                            delivery_time += (int) (rideRouteResult.getPaths().get(0).getDuration() / 60);
                                            delivery_time += 15;
                                            how_long.setText(delivery_time + "分钟");
                                        }
                                    }
                                }
                            });

                            RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(shop_data.get(i).getLat(), shop_data.get(i).getLng()), new LatLonPoint(locationData.getLat(), locationData.getLng()));
                            RouteSearch.RideRouteQuery query1 = new RouteSearch.RideRouteQuery(fromAndTo);
                            routeSearch.calculateRideRouteAsyn(query1);
                        } catch (AMapException e) {
                            throw new RuntimeException(e);
                        }

                        Bitmap decodedImage = BitmapFactory.decodeByteArray(shop_data.get(i).getShop_image(), 0, shop_data.get(i).getShop_image().length);
                        shop_image.setImageBitmap(decodedImage);

                        shop_name.setText(shop_data.get(i).getShop_name());
                        shop_star.setText(shop_data.get(i).getShop_star() + "分");
                        shop_sold_in_month.setText("月售 " + shop_data.get(i).getShop_sold());
                        String distance = String.format("%.2f", AMapUtils.calculateLineDistance(new LatLng(shop_data.get(i).getLat(), shop_data.get(i).getLng()), new LatLng(locationData.getLat(), locationData.getLng())) / 1000.0);
                        if (Double.parseDouble(distance) < 3) {
                            if ((surcharge + 3.15 - shop_data.get(i).getCan_reduce_the_delivery_fee()) > 0) {
                                how_many_delivery_fee.setText("配送 约¥" + String.format("%.2f", (surcharge + 3.15 - shop_data.get(i).getCan_reduce_the_delivery_fee())));
                            }
                            else {
                                how_many_delivery_fee.setText("免配送费");
                            }
                        }
                        else {
                            if (((Double.parseDouble(distance) - 3) / 0.1 * 0.2) + surcharge + 3.15 - shop_data.get(i).getCan_reduce_the_delivery_fee() > 0) {
                                how_many_delivery_fee.setText("配送 约¥" + String.format("%.2f", ((Double.parseDouble(distance) - 3) / 0.1 * 0.2) + surcharge + 3.15 - shop_data.get(i).getCan_reduce_the_delivery_fee()));
                            }
                            else {
                                how_many_delivery_fee.setText("免配送费");
                            }
                        }
                        how_far.setText(distance + "km");

                        if (shop_data.get(i).getNew_custom_receive_reduce_how_many_money() == 0) {
                            is_open_new_custom_receive_a_discount.setVisibility(View.GONE);
                        }
                        else {
                            is_open_new_custom_receive_a_discount.setVisibility(View.VISIBLE);
                            new_custom_receive_a_discount_text_view.setText("新客減" + shop_data.get(i).getNew_custom_receive_reduce_how_many_money());
                        }

                        if (shop_data.get(i).getCollect_reduce_how_many_money() == 0) {
                            is_open_coupon_collect_and_get_give.setVisibility(View.GONE);
                        }
                        else {
                            is_open_coupon_collect_and_get_give.setVisibility(View.VISIBLE);
                            coupon_collect_and_get_give_text_view.setText("收藏领" + shop_data.get(i).getCollect_reduce_how_many_money() + "元券");
                        }

                        int finalI = i;
                        click_this_shop.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(root.getContext(), Check_Shop_Data_Page.class);
                                intent.putExtra("email", shop_data.get(finalI).getEmail());
                                intent.putExtra("user_location", location_text.getText().toString());
                                intent.putExtra("delivery_time", delivery_time);
                                intent.putExtra("shop_name", shop_data.get(finalI).getShop_name());
                                intent.putExtra("packing_fee", shop_data.get(finalI).getPacking_fee());
                                if (Double.parseDouble(distance) < 3) {
                                    intent.putExtra("delivery_fee", surcharge + 3.15);
                                }
                                else {
                                    intent.putExtra("delivery_fee", ((Double.parseDouble(distance) - 3) / 0.1 * 0.2) + surcharge + 3.15);
                                }
                                intent.putExtra("reduce_how_many_delivery_fee", shop_data.get(finalI).getCan_reduce_the_delivery_fee());
                                intent.putExtra("user_name", user_name);
                                intent.putExtra("user_phone_number", user_phone_number);
                                intent.putExtra("user_sex", user_sex);
                                intent.putExtra("how_long", Double.parseDouble(distance));
                                intent.putExtra("user_email", email);
                                startActivity(intent);
                            }
                        });

                        set_shop_data.addView(view);
                    }
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        root = inflater.inflate(R.layout.fragment_home__page, container, false);

        viewList.add(LayoutInflater.from(root.getContext()).inflate(R.layout.home_page_first_view_page, null));
        viewList.add(LayoutInflater.from(root.getContext()).inflate(R.layout.home_page_second_view_page, null));

        Loading_Is_Login_Thread loadingIsLoginThread = new Loading_Is_Login_Thread();
        loadingIsLoginThread.start();

        search_text = root.findViewById(R.id.search_text);
        search = root.findViewById(R.id.search);
        view_page = root.findViewById(R.id.view_page);
        set_location = root.findViewById(R.id.set_location);
        location_text = root.findViewById(R.id.location_text);
        set_shop_data = root.findViewById(R.id.set_shop_data);

        if (locationData.getLocation().isEmpty()) {
            location_text.setText("定位中…");
        }
        else {
            location_text.setText(locationData.getLocation());
            Loading_Shop_Data_Thread loadingShopDataThread = new Loading_Shop_Data_Thread();
            loadingShopDataThread.start();
        }

        search_text.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textview = new TextView(root.getContext());
                textview.setTextSize(15);
                textview.setTextColor(Color.rgb(128, 128, 128));
                return textview;
            }
        });

        Loop_Text_Thread loopTextThread = new Loop_Text_Thread();
        loopTextThread.start();

        view_page.setAdapter(new ViewPagerAdapter(viewList));

        set_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (locationData.getLocation().isEmpty()) {
                    Toast.makeText(root.getContext(), "请先加载位置", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();
                    Loading_Email_Thread loadingEmailThread = new Loading_Email_Thread();
                    loadingEmailThread.start();
                }
            }
        });

        return root;
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
        LayoutInflater inflater1 = LayoutInflater.from(root.getContext());
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    public void return_shop_lat(String place, String city) {
        Geocoder geocoder = new Geocoder(root.getContext(), Locale.getDefault());
        try {
           List<Address> addresses = geocoder.getFromLocationName(place, 1);
           if (addresses != null && !addresses.isEmpty()) {
               lat_temp = addresses.get(0).getLatitude();
               lng_temp = addresses.get(0).getLongitude();
           }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (data != null) {
                    locationData.setLocation(data.getStringExtra("address"));
                    locationData.setDistrict(data.getStringExtra("district"));
                    locationData.setLat(data.getDoubleExtra("lat", 0));
                    locationData.setLng(data.getDoubleExtra("lng", 0));
                    locationData.setCity(data.getStringExtra("city"));
                    locationData.setProvince(data.getStringExtra("province"));
                    user_name = data.getStringExtra("user_name");
                    user_sex = data.getStringExtra("user_sex");
                    user_phone_number = data.getStringExtra("user_phone_number");
                    location_text.setText(locationData.getLocation());

                    set_shop_data.removeAllViews();
                    shop_data.clear();
                    Loading_Shop_Data_Thread loadingShopDataThread = new Loading_Shop_Data_Thread();
                    loadingShopDataThread.start();
                }
            }
        }
    }
}